import { omitBy } from 'lodash-unified'
import { ref } from 'vue'

import { menuApi } from '@/apis'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { TableOptions, useTableRef } from '@/hooks'

export function useTable() {
  const tableConfig = ref({
    loading: false,
    toolbarConfig: {
      custom: true,
      refresh: true,
      zoom: true,
      slots: {
        buttons: 'toolbar_buttons'
      }
    },
    formConfig: {
      items: [
        {
          field: 'menuName',
          title: '菜单名称',
          itemRender: {
            name: TABLE_ITEM_RENDER.AInput,
            props: {
              placeholder: '请输入菜单名称'
            }
          }
        },
        {
          field: 'status',
          title: '状态',
          itemRender: {
            name: TABLE_ITEM_RENDER.ASelect,
            props: {
              placeholder: '菜单状态'
            }
          }
        },
        {
          itemRender: {
            name: TABLE_RENDERER.FormItemBtns
          }
        }
      ]
    },
    columns: [
      {
        field: 'menuName',
        title: '菜单名称',
        treeNode: true
      },
      {
        field: 'icon',
        title: '图标',
        slots: {
          default: 'icon'
        }
      },
      {
        field: 'orderNum',
        title: '排序'
      },
      {
        field: 'perms',
        title: '权限标识'
      },
      {
        field: 'component',
        title: '组件路径'
      },
      {
        field: 'status',
        title: '状态',
        slots: {
          default: 'status'
        }
      },
      {
        field: 'createTime',
        title: '创建时间',
        formatter: TABLE_FORMAT.Date
      },
      {
        title: '操作',
        slots: {
          default: 'operation'
        }
      }
    ],
    proxyConfig: {
      seq: true,
      form: true,
      ajax: {
        query: async ({ form }) => {
          form = omitBy(form, value => {
            return value === null
          })

          return await menuApi.getMenuList({
            ...form
          })
        }
      }
    },
    treeConfig: {
      transform: true,
      rowField: 'menuId',
      parentField: 'parentId',
      expandAll: false
    }
  } as TableOptions)

  const tableRefHook = useTableRef(tableConfig)

  return {
    tableConfig,
    tableRefHook
  }
}
